package com.hue.workqueue;

import com.hue.utils.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/*
    工作队列模式：消费者
 */
public class Customer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接
        Connection connection = ConnectionUtils.getConnection();
        //获取频道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare("work_queue",true,false,false,null);
        //设置消费者每次消费的消息数
        channel.basicQos(1);
        //创建消费者接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到的消息："+new String(body));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //确认消息
                /*
                    参数含义：
                        1.消息id
                        2.false表示只有当前消息被处理
                 */
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //监听消息
        channel.basicConsume("work_queue", true,consumer);
    }
}
